import { z } from "zod";
import { codeartsrepoRequest, buildUrl } from "../common/utils.js";
import { WebhookSchema } from "../common/types.js";

// 查询指定仓库的webhook
export const ListHooksSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
});

// 为指定仓库添加hook
export const AddHooksSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  url: z.string().describe("Webhook URL"),
  events: z.array(z.string()).describe("事件类型，如push, merge_request等"),
  enabled: z.boolean().optional().describe("是否启用，默认为true"),
  token: z.string().optional().describe("安全令牌"),
  ssl_verification: z.boolean().optional().describe("是否验证SSL证书"),
});

// 删除指定仓库的hook
export const DeleteHooksSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_id: z.string().describe("仓库ID"),
  hook_id: z.string().describe("Webhook ID"),
});

// 功能实现
export async function listHooks(
  projectId: string,
  repoId: string
) {
  const url = `https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/hooks`;
  const response = await codeartsrepoRequest(url);
  return z.array(WebhookSchema).parse(response);
}

export async function addHooks(
  projectId: string,
  repoId: string,
  options: {
    url: string;
    events: string[];
    enabled?: boolean;
    token?: string;
    ssl_verification?: boolean;
  }
) {
  const response = await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/hooks`, {
    method: "POST",
    body: {
      url: options.url,
      events: options.events,
      enabled: options.enabled !== undefined ? options.enabled : true,
      token: options.token,
      ssl_verification: options.ssl_verification
    }
  });
  
  return WebhookSchema.parse(response);
}

export async function deleteHooks(
  projectId: string,
  repoId: string,
  hookId: string
) {
  await codeartsrepoRequest(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repositories/${repoId}/hooks/${hookId}`, {
    method: "DELETE"
  });
  
  return { success: true };
} 